//
//  ZG2DBCodeVC.m
//  扫码
//
//  Created by 鲍志刚 on 16/3/30.
//  Copyright © 2016年 鲍志刚. All rights reserved.
//

#import "ZGQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "ZGPreView.h"

#import <SafariServices/SafariServices.h>

#import "NetworkTools.h"


@interface ZGQRCodeVC ()<AVCaptureMetadataOutputObjectsDelegate>


@property (nonatomic, strong) AVCaptureDeviceInput *input;

@property (nonatomic, strong) AVCaptureMetadataOutput *output;

@property (nonatomic, strong) AVCaptureSession *session;

//@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic, strong) ZGPreView *preview;

@property(nonatomic,strong)NSDictionary *parameters;




@end

@implementation ZGQRCodeVC

#pragma mark - 懒加载
-(NSDictionary *)parameters{
    if (!_parameters) {
        _parameters = [[NSDictionary alloc]init];
    }
    return _parameters;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUpUI];
    
    self.tabBarItem.image = [UIImage imageNamed:@"tabbar_home"];
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"扫一扫" style:UIBarButtonItemStylePlain target:self action:@selector(sweepBtn)];
    
}

#pragma mark - 设置ui 
- (void)setUpUI{
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"find_icon_sao"] style:UIBarButtonItemStylePlain target:self action:@selector(sweepBtn)];
    
    
    self.navigationItem.title = @"二维码";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backBtn)];
    
    [self.navigationItem.leftBarButtonItem setEnabled:NO];
    
}


#pragma mark - 返回
- (void)backBtn {
    
    [self.session stopRunning];
    
    [self.preview removeFromSuperview];
    
}

#pragma mark - 扫一扫
- (void)sweepBtn {
    
    [self.navigationItem.leftBarButtonItem setEnabled:YES];

     NSString *mediaType = AVMediaTypeVideo;
     
     AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
     
     if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
     
     UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"访问受限" message:@"请在iPhone的“设置”-“隐私”-“相机”功能中，找到“XXXX”打开相机访问权限" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
     
     [alert show];
         
         
             
     return;
     
     }

//    NSLog(@"扫一扫");
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:mediaType];
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];

    self.output = [AVCaptureMetadataOutput new];
    
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
     self.session = [AVCaptureSession new];
    
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    //4. 特殊的layer,展示用户扫描到的内容 --> 需要一个会话类的对象
//        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
//        self.previewLayer.frame = self.view.bounds;
//        [self.view.layer addSublayer:self.previewLayer];
    
    self.preview = [[ZGPreView alloc] initWithFrame:self.view.bounds];
    self.preview.session = self.session;
    [self.view addSubview:self.preview];
    
     [self.session startRunning];
    
}
//metadataObjects: 扫描到的数据
//fromConnection: 连接
#pragma mark - 代理方法，二维码扫扫描到的数据
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //1. 停止扫描
    [self.session stopRunning];
    
    //2. 删除特殊的layer
//    [self.previewLayer removeFromSuperlayer];
    [self.preview removeFromSuperview];
    
    NSLog(@"%@",metadataObjects);
    
    //3. 获取数据
    //AVMetadataMachineReadableCodeObject: 这个类如果不知道, 可以打印一下
    for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
        
        
        NSLog(@"obj:%@",[obj.stringValue substringWithRange:NSMakeRange(34, 6)]);
        
        //保存信息  http://192.168.0.114:8080/APP2/SweepServlet?method=saveSweep&number=12
        [[NetworkTools sharedTools] GET:[NSString stringWithFormat:@"SweepServlet?method=saveSweep&number=%d&city=beijing",[obj.stringValue substringWithRange:NSMakeRange(34, 6)].intValue] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
//            NSLog(@"%@",responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"%@",error);
            
        }];

        
        /*
         打印结果
         (
         "<AVMetadataMachineReadableCodeObject: 0x17581a30, type=\"org.iso.QRCode\", bounds={ 0.4,0.2 0.3x0.5 }>corners { 0.4,0.7 0.7,0.7 0.7,0.2 0.4,0.2 }, time 10693578769458, stringValue \"http://y.cpzs.org/2100031000001000052878\""
         )
         */
//        4. 将来就在这里进行数据处理
        
        // 判断网页并弹出
        if ([obj.stringValue containsString:@"http"]) {
            
            //4.1 创建SafariVC
            SFSafariViewController *sfVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:obj.stringValue]];
            
            //4.2 弹出SafariVC
            [self presentViewController:sfVC animated:YES completion:nil];
            
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
